﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Web.Security;
using System.Windows.Forms;
using Logic;
using Model;
using Newtonsoft.Json;
using Utils;
using Wrapper;

namespace DYRecommand
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        TB_Sale_Info curSaleInfo = null;

        System.Timers.Timer saleTimer = null;

        private void PrintLogBackGround(string msg)
        {
            if (this.WindowState != FormWindowState.Minimized)
            {
                string content = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ffffff") + ":" + msg + "\r\n";
                if (richTextBox1.Lines.Length > 500)
                {
                    richTextBox1.Clear();
                }
                richTextBox1.AppendText(content);
                richTextBox1.ScrollToCaret();
            }

            Log.PrintLog(msg);
        }

        private delegate void NewTaskDelegate(string msg);

        private void PrintLog(string msg)
        {
            this.Invoke(new NewTaskDelegate(PrintLogBackGround), msg);
        }

        private void saleTimer_Tick(object sender, System.Timers.ElapsedEventArgs e)
        {
            if (DateTime.Now.Hour < 7)
            {
                PrintLog(" 非 工作时间");
                return;
            }
            if (DateTime.Now.Hour == 22 && DateTime.Now.Minute > 40)
            {
                PrintLog(" 非 工作时间");
                return;
            }
            if (DateTime.Now.Hour > 22)
            {
                PrintLog(" 非 工作时间");
                return;
            }

            

            try
            {
                saleTimer.Stop();

                cleanHistoryFile();

                PrintLog("定时器 启动");
                if (curSaleInfo == null)
                {
                    PrintLog("当前的店员数据为空， 从数据库中获取");
                    curSaleInfo = SaleInfoLogic.GetNeedRecommand();
                }
                else
                {
                    PrintLog("内存中有 未处理完成的店员数据，直接使用");
                }

                if (curSaleInfo != null)
                {
                    //更新 该账号已经被占用
                    curSaleInfo.bUsed = 1;
                    curSaleInfo.UsedName = ConfigurationManager.AppSettings["UsedName"];
                    curSaleInfo.UsedTime = DateTime.Now;
                    SaleInfoLogic.UpdateModel(curSaleInfo);

                    PrintLog("有需要推荐的店员数据, " + JsonConvert.SerializeObject(curSaleInfo));

                    TB_Run_Info runInfo = RunInfoLogic.GetModel();
                    int maxRecommandCount = Convert.ToInt32(runInfo.MaxCount);//Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["MaxRecommandCount"]);

                    List<TB_Phone_Info> listPhoneInfo = PhoneInfoLogic.GetNeedRecommandModelByRefereePhone(curSaleInfo.SaleAccount, maxRecommandCount);


                    if (listPhoneInfo == null)
                   {
                        listPhoneInfo = new List<TB_Phone_Info>();
                   }

                    if (listPhoneInfo != null )
                    {
                        PrintLog("进行登录操作");
                        string sId = FormsAuthentication.HashPasswordForStoringInConfigFile(Guid.NewGuid().ToString(), "MD5");
                        DYJFLogic logic = new DYJFLogic(sId);
                        
                        string result = Login(logic, curSaleInfo.SaleAccount, curSaleInfo.SalePwd);
                        if (string.IsNullOrEmpty(result))
                        {
                            
                            PrintLog("登录成功");

                            //查询酬金
                            BRBD(curSaleInfo.SaleAccount, logic);

                            //查询推荐
                            QEBData(curSaleInfo.SaleAccount, logic);

                            int min = 35000;
                            int max = 60000;
                            int wait = min;
                            int j = 0;


                            for (int i = 0; i < listPhoneInfo.Count; i++)
                            {
                                j++;
                                wait = min + (j * 1000);
                                if (wait >= max)
                                {
                                    j = 0;
                                    wait = min;
                                }
                                PrintLog("等待" + wait + "毫秒");
                                System.Threading.Thread.Sleep(wait);
                                TB_Phone_Info tempPhoneInfo = listPhoneInfo[i];
                                PrintLog("要推荐的数据为：" + Newtonsoft.Json.JsonConvert.SerializeObject(tempPhoneInfo));
                                TB_App_Info appInfo = AppInfoLogic.GetModelById(tempPhoneInfo.AppId);
                                if (appInfo == null)
                                {
                                    PrintLog("没有需要推荐的应用数据");
                                }
                                else
                                {
                                    result = SendInfo(logic, tempPhoneInfo.Phone, appInfo.BusCode, appInfo.busName);
                                    if (string.IsNullOrEmpty(result))
                                    {//推荐成功
                                        PrintLog("推荐成功");
                                        int rel = PhoneInfoLogic.UpdateRecommand(tempPhoneInfo);
                                        if (rel > 0)
                                        {
                                            PrintLog("更新数据成功");
                                        }
                                    }
                                    else
                                    {
                                        PrintLog("推荐失败，失败原因：" + result);
                                    }
                                }
                            }

                            
                        }
                        else
                        {//登录失败
                            PrintLog(result);
                        }

                        //首先判断今天是否达到了最大推荐
                        //更新为未使用
                        int hasRecommand = PhoneInfoLogic.HasRecommandCount(curSaleInfo.SaleAccount);
                        if (hasRecommand >= maxRecommandCount)
                        {
                            curSaleInfo.bLimit = 1;
                            curSaleInfo.bUsed = 0;
                            curSaleInfo.LimitTime = DateTime.Now;
                            SaleInfoLogic.UpdateModel(curSaleInfo);

                            curSaleInfo = null;
                        }

                        

                    }
                    else
                    {
                        //首先判断今天是否达到了最大推荐
                        //更新为未使用
                        int hasRecommand = PhoneInfoLogic.HasRecommandCount(curSaleInfo.SaleAccount);
                        if (hasRecommand >= maxRecommandCount)
                        {
                            PrintLog("达到今日最大推荐数，更新为未使用，及受限");
                            curSaleInfo.bLimit = 1;
                            curSaleInfo.bUsed = 0;
                            curSaleInfo.LimitTime = DateTime.Now;
                            SaleInfoLogic.UpdateModel(curSaleInfo);

                            curSaleInfo = null;
                        }
                        else
                        {
                            PrintLog("没有到达今天最大推荐个数，但是没有需要推荐的号码数据，更新为 没有可用推荐资源状态");
                            //更新店员状态
                            int updateRel = SaleInfoLogic.UpdateModel2NoRecommand(curSaleInfo);
                            if (updateRel > 0)
                            {
                                curSaleInfo = null;
                                PrintLog("更新店员状态成功");
                            }
                            else
                            {
                                PrintLog("更新店员状态失败");
                            }
                        }
                    }

                }
                else
                {
                    PrintLog("没有需要推荐的数据");
                }

            }
            catch (Exception ex)
            {
                PrintLog(ex.Message + "\r\n" + ex.Source + "\r\n" + ex.StackTrace);
            }
            finally
            {
                saleTimer.Start();
            }
        }



        private string Login(DYJFLogic logic, string phone, string pwd)
        {
            string result = logic.Get_Login_Show();
            bool suc = logic.DownImage();
            if (suc)
            {
                CodeInfo codeInfo = logic.RecognizeRadon();

                if (codeInfo.ResultCode.Length == 4)
                {
                    suc = logic.Login(phone, pwd, codeInfo.ResultCode);
                    if (!suc)
                    {
                        result = "登录失败";
                    }
                    else
                    {
                        result = "";
                    }
                }
                else
                {
                    result = "验证码识别失败";
                }
            }
            else
            {
                result = "验证码下载失败";
            }
            return result;
        }


        private string SendInfo(DYJFLogic logic, string phone, string busCode, string busName)
        {
            string error = "";
            try
            {
                string result = logic.Post_Recommand(phone);

                result = result.Replace("\n", "");
                if (result == "1")
                {
                    error = "手机号码不能为空！";
                }
                else if (result == "2")
                {
                    error = "手机号格式不正确,请重新输入！";
                }
                else if (result == "3")
                {
                    error = "手机号不属于河南移动号段！";
                }
                else
                {
                    result = logic.Post_SendInfo(phone, busCode, busName);

                    result = result.Replace("\n", "");
                    if (result == "1")
                    {
                        error = "";
                    }
                    else if (result == "5")
                    {
                        error = "您的操作频繁，请30秒后再试！";
                    }
                    else if (result == "6")
                    {
                        error = "对同一用户每天最多操作2次！";
                    }
                    else if (result == "7")
                    {
                        error = "尊敬的用户你好，晚上23:00至早上6:00禁止推荐业务，请见谅！！！";
                    }
                    else if (result == "0")
                    {
                        error = "发送失败！";
                    }
                    else if (result == "12")
                    {
                        error = "必须是同一地市才可推荐！";
                    }
                    else if (result == "2")
                    {
                        error = "登录身份校验错误";
                    }

                }
            }
            catch (Exception ex)
            {
                error = ex.Message + "\r\n" + ex.Source + "\r\n" + ex.StackTrace;
            }
            return error;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            System.Net.ServicePointManager.DefaultConnectionLimit = 512;

            saleTimer = new System.Timers.Timer(Convert.ToInt32(ConfigurationManager.AppSettings["RadonTimeOut"]) * 1000);
            saleTimer.Elapsed += saleTimer_Tick;
            saleTimer.Start();

            PrintLog("程序开始启动");

            bool suc = false;
            if (File.Exists("temp"))
            {//存在异常数据， 恢复数据
                PrintLog("恢复上次异常数据");
                using (FileStream fileStream = new FileStream("temp", FileMode.Open))
                {
                    StreamReader sr = new StreamReader(fileStream);
                    //定位操作点,begin 是一个参考点     
                    sr.BaseStream.Seek(0, SeekOrigin.Begin);
                    string strSaleInfo = sr.ReadToEnd();
                    TB_Sale_Info tempSale;
                    try
                    {
                        tempSale = JsonConvert.DeserializeObject<TB_Sale_Info>(strSaleInfo);
                    }
                    catch
                    {
                        PrintLog("异常数据格式有误，无法转换有效实体，放弃此数据");
                        File.Delete("temp");
                        return;
                    }
                    try
                    {
                        tempSale.bUsed = 0;
                        SaleInfoLogic.UpdateModel(tempSale);
                        PrintLog("异常数据状态恢复成功");
                        suc = true;
                    }
                    catch
                    {
                        PrintLog("异常数据更新失败，请恢复网络后，重新打开本程序");
                    }
                    finally
                    {
                        sr.Close();
                        sr = null;
                    }
                }

                if (suc)
                {
                    File.Delete("temp");
                }
            }
        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            try
            {
                if (curSaleInfo != null)
                {
                    PrintLog("当前账户为：" + JsonConvert.SerializeObject(curSaleInfo));
                    PrintLog("更新使用状态为 0");
                    curSaleInfo.bUsed = 0;
                    SaleInfoLogic.UpdateModel(curSaleInfo);

                    curSaleInfo = null;
                }
            }
            catch (Exception ex)
            {//更新数据异常， 为保证数据库同步， 本地记录相关数据
                using (FileStream fileStream = new FileStream("temp", FileMode.Create))
                {
                    StreamWriter writer = new StreamWriter(fileStream);
                    writer.Write(JsonConvert.SerializeObject(curSaleInfo));
                    writer.Flush();
                    writer.Close();
                    fileStream.Close();
                }
            }

        }

        private void Form1_SizeChanged(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized) //判断是否最小化
            {
                this.ShowInTaskbar = false; //不显示在系统任务栏
                notifyIcon1.Visible = true; //托盘图标可见
            }
        }

        private void notifyIcon1_DoubleClick(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.WindowState = FormWindowState.Normal;
                notifyIcon1.Visible = false;
                this.ShowInTaskbar = true;
            }
        }

        /// <summary>
        /// 获取上个月的酬金
        /// </summary>
        /// <param name="saleAccount"></param>
        /// <param name="logic"></param>
        private void BRBD(string saleAccount, DYJFLogic logic)
        {
            PrintLog("开始查询上月酬金");
            string feeDate = DateTime.Now.AddMonths(-1).ToString("yyyy-MM");
            if (!SaleFeeLogic.ExistsSuc(feeDate, saleAccount))
            {
                string[] brbd = logic.BRBD(feeDate);
                int suc = Convert.ToInt32(brbd[0]);
                int fail = Convert.ToInt32(brbd[1]);
                TB_Sale_Fee saleFee = new TB_Sale_Fee()
                {
                    FeeDate = feeDate,
                    FeeFailCount = fail,
                    FeeSucCount = suc,
                    SaleAccount = saleAccount,
                    SelfFee = Convert.ToDecimal(suc * 1.4),
                    ShopFee = Convert.ToDecimal(suc * 0.6),
                    STime = DateTime.Now,
                    AllFee = suc * 2

                };

                SaleFeeLogic.Insert(saleFee);
            }

            PrintLog("查询上月酬金结束");
            
        }

        /// <summary>
        /// 查询本月推荐数情况
        /// </summary>
        /// <param name="saleAccount"></param>
        /// <param name="logic"></param>
        private void QEBData(string saleAccount, DYJFLogic logic)
        {
            PrintLog("开始查询本月推荐情况");
            string recDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(1).AddDays(-1).ToString("yyyy-MM-dd");

            string[] qebData = logic.QEBDatas(recDate);
            int suc = Convert.ToInt32(qebData[0]);
            int fail = Convert.ToInt32(qebData[1]);
            TB_Sale_Rec saleRec = new TB_Sale_Rec()
            {
                RecDate = recDate,
                RecFailCount = fail,
                RecSucCount = suc,
                SaleAccount = saleAccount,
                STime = DateTime.Now
            };

            SaleRecLogic.Insert(saleRec);

            PrintLog("查询本月推荐情况结束");
        }

        private void cleanHistoryFile()
        {
            DirectoryInfo imgInfo = new DirectoryInfo("dyjfimg\\");

            DirectoryInfo cacheInfo = new DirectoryInfo("dyjfcache\\");

            foreach (DirectoryInfo temp in imgInfo.GetDirectories())
            {
                DateTime tempDate = temp.CreationTime;
                if (tempDate < DateTime.Now.AddDays(-1))
                {
                    temp.Delete(true);
                }
            }

            foreach (DirectoryInfo temp in cacheInfo.GetDirectories())
            {
                DateTime tempDate = temp.CreationTime;
                if (tempDate < DateTime.Now.AddDays(-1))
                {
                    temp.Delete(true);
                }
            }

        }

    }

}
